package com.china08.yxyapi.api.manage.tec.teaching.scoreport.createexam;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.config.RabbitConfig;
import com.china08.yxyapi.entity.mg.scoreport.ExamStudent;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.mg.scoreport.ExamStudentRepository;
import com.china08.yxyapi.service.mg.impl.ExamServiceImpl;
import com.china08.yxyapi.util.SpringContextUtil;
import com.china08.yxyapi.util.YxUserPointsUtilV3;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;

/**
 * 导入考试模板进行解析
 * 
 */
@CrossOrigin
@RestController
public class ImportExamController extends YxyApiBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImportExamController.class);

    @Autowired
    private ExamStudentRepository examStudentRepository;

    @Autowired
    private ExamServiceImpl examServiceImpl;

    @Autowired
    private YxUserPointsUtilV3 yxUserPointsUtilV3;

    @RequestMapping(value = "/api_yw/manage/tec/teaching/scoreport/createexam/import", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel uploadExcel(@RequestParam(value = "file", required = false) MultipartFile multipartFile,
            HttpServletResponse response, HttpServletRequest request) {
        RespModel respModel = new RespModel();

        String userId = getProfile(request, response).getId();

        Workbook wb = null;
        try {
            wb = WorkbookFactory.create(multipartFile.getInputStream());
        } catch (InvalidFormatException e) {
            LOGGER.error("不是有效的Excel格式", e);
            respModel.setErrorFlag(false);
            respModel.setErrorMsg("不是有效的Excel格式");
            return respModel;
        } catch (Exception e) {
            LOGGER.error("解析Excel文件异常", e);
            respModel.setErrorFlag(false);
            respModel.setErrorMsg("解析Excel文件异常");
            return respModel;
        }

        ExcelBackData excelBackData = examServiceImpl.parsingExcel(wb, new ExcelBackData(), userId);
        if (!excelBackData.errorFlag) {
            respModel.setErrorFlag(false);
            respModel.setErrorMsg(excelBackData.errorMsg);
            return respModel;
        }

        // 清空历史数据
        List<ExamStudent> examStuLst = examStudentRepository.findByExam(excelBackData.examStuLst.get(0).getExam());
        examStudentRepository.delete(examStuLst);

        // 对Excel数据进行保存
        for (ExamStudent examStudent : excelBackData.examStuLst) {
            ExamStudent examStu = null;
            examStu = examStudentRepository.findByExamAndStudentId(examStudent.getExam().getId(),
                    examStudent.getStudentId());
            if (examStu == null) {
                examStu = examStudent;
            } else {
                examStu.setStuTotalScore(examStudent.getStuTotalScore());
                examStu.setStuQuesScores(examStudent.getStuQuesScores());
            }
            examStudentRepository.save(examStu);
        }

        // 组装mq进行成绩分析
        SpringContextUtil.getBean(RabbitTemplate.class).convertAndSend(RabbitConfig.ClASS_EXAM_REPORT,
                excelBackData.examId);

        // 追加积分
        yxUserPointsUtilV3.uploadScore(userId);

        // 返回前台告诉是否解析成功
        respModel.setErrorFlag(true);
        respModel.setId(excelBackData.examId);
        return respModel;
    }

    /**
     * 响应参数
     * 
     */
    public static class RespModel extends YxyApiRespModel {
        // 考试id
        public String id;

        // 错误标识
        public boolean errorFlag;

        // 错误信息
        public String errorMsg;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public boolean isErrorFlag() {
            return errorFlag;
        }

        public void setErrorFlag(boolean errorFlag) {
            this.errorFlag = errorFlag;
        }

        public String getErrorMsg() {
            return errorMsg;
        }

        public void setErrorMsg(String errorMsg) {
            this.errorMsg = errorMsg;
        }
    }

    /**
     * 解析时返回数据
     *
     */
    public class ExcelBackData {
        // 学生考试信息
        public List<ExamStudent> examStuLst;
        // 考试信息Id
        public String examId;

        // 错误标识
        public boolean errorFlag;
        // 错误信息
        public String errorMsg;
    }
}
